<?
require_once('ConverterBase.php');

class CurrencyConverter extends ConverterBase {
	private $currencySymbol=null,$currencyCode=null,$amountOnly= false;

	// ACCESSORS
	public function setCurrencySymbol($value) { $this->currencySymbol= $value; return $this; }
	public function getCurrencySymbol() { return $this->currencySymbol; }

	public function setCurrencyCode($value) { $this->currencyCode= $value; return $this; }
	public function getCurrencyCode() {
		if (is_null($this->currencyCode)) {
			$locales= localeconv();
			$this->currencyCode= $locales['int_curr_symbol'];
		}
		return $this->currencyCode;
	}
	
	public function setAmountOnly($value) { $this->amountOnly= $value; return $this; }
	public function getAmountOnly() { return $this->amountOnly; }

	protected function toDatatype($string) {
		if (!trim($string)) return null;
		else if (ereg_replace("[^0-9]",'',$string)=== '')
			throw new ConverterException($this,'unable_to_convert_empty_string');
		return new Currency(floatval(ereg_replace("[^0-9\+-\.]",'',$string)),$this->getCurrencyCode());
	}
	protected function toString($currency) {
		$this->expectObject('Currency',$currency);
		$number= $currency->getAmount();
		
		$locale = localeconv();
		// Sign specifications
		if ($number> 0) {
			$sign = $locale['positive_sign'];
			$sign_posn = $locale['p_sign_posn'];
			$sep_by_space = $locale['p_sep_by_space'];
			$cs_precedes = $locale['p_cs_precedes'];
		} else {
			$sign = $locale['negative_sign'];
			$sign_posn = $locale['n_sign_posn'];
			$sep_by_space = $locale['n_sep_by_space'];
			$cs_precedes = $locale['n_cs_precedes'];
		}
		// overwrite symbol
		if ($this->getCurrencySymbol())
			$currency= $this->getCurrencySymbol();
		// if no symbol is given overwrite with code and append as opposed to preced
		else {
			$currency= $this->getCurrencyCode();
			$cs_precedes= 0;
		}

		// Currency format
		$number= number_format(
			$number,
			$locale['frac_digits'],
			$locale['mon_decimal_point'],
			$locale['mon_thousands_sep']
		);
		if (!$this->getAmountOnly()) {
			$space = $sep_by_space ? ' ' : '';
			if ($cs_precedes) $number = "$currency$space$number";
			else $number.= "$space$currency";
		}
		// position sign
		switch($sign_posn) {
			case 0: $n = "($number)"; break;
			case 2:
			case 4: $n = "$number$sign"; break;
			case 1:
			case 3:
			default: $n = "$sign$number"; break;
		}
		return $number;
	}
}
